package ws.cmpe451.group7.ourcity.webservice;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import ws.cmpe451.group7.ourcity.webservice.exception.GeneralIllegalArgumentException;
import cmpe451.group7.ourcity.recommendation.FreebaseQuery;
import cmpe451.group7.ourcity.util.JSONUtils;

/**
 * Servlet for testing Freebase usage
 * 
 * @author gokhan
 * 
 */
@Controller
public class TestFreebaseServlet {
	static List<String> parameters = new ArrayList<String>();
	static {
		parameters.add("type");
		parameters.add("query");
	}

	/**
	 * This is a test controller for testing the city & country auto complete
	 * features
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/freebase")
	protected void freebaseRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		Callable func = new Callable() {
			@Override
			public void call(HttpServletRequest request,
					HttpServletResponse response, PrintWriter responseWriter,
					Map<String, String[]> parameters)
					throws GeneralIllegalArgumentException, JSONException {

				String type = parameters.get("type")[0];
				String query = parameters.get("query")[0];

				List<String> suggestions;

				switch (type) {
				case "country":
					suggestions = FreebaseQuery.completeCountry(query);
					break;
				case "city":
					suggestions = FreebaseQuery.completeCity(query);
					break;
				case "cityNcountry":
					suggestions = FreebaseQuery.completeCity("turkey", query);
					break;
				default:
					throw new GeneralIllegalArgumentException(String.format(
							"%s method is not implemented", type));
				}

				JSONUtils.JSONListWriter(suggestions, responseWriter);
			}
		};

		ControllerWrapper.wrapMethod(request, response, func, parameters);
	}

}
